﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class DocReceivedController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly DocReceivedService _docReceivedService;
    private readonly UserService _adminUserService;
    private readonly DocCatService _docCatService;
    private readonly AttmentService _attment;
    public DocReceivedController(
        ApplicationContext applicationContext,
        DocReceivedService docReceivedService,
        DocCatService docCatService,
        UserService adminUserService,
        AttmentService attment)
    {
        _applicationContext = applicationContext;
        _docReceivedService = docReceivedService;
        _docCatService = docCatService;
        _adminUserService = adminUserService;
        _attment = attment;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.DocReceived_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] DocReceivedQuery query, int cid = 0)
    {
        ILoginUserInfo user = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        query.Cids = cid == 0 ? null : new int[] { cid };
        query.Uids = await _adminUserService.UserPostAsUids(user);
        if (query.ExportExcel)
        {
            PagedInfo<ViewDocReceivedAndCate> list = await _docReceivedService.GetPageListAsync(query);
            string sFileName = ExcelHelperAction.ExportExcel(list.Result, "收文列表");
            return Success(new { FilePath = "/export/" + sFileName, fileName = sFileName });
        }
        else
        {
            IEnumerable<DocCat> catList = await _docCatService.CategoryListAsync(user, (int)ModelTypeEnum.ModelType.来文收文);
            PagedInfo<ViewDocReceivedAndCate> pagedList = await _docReceivedService.GetPageListAsync(query);
            return Success(new { count = pagedList.TotalNum, data = pagedList.Result, catList });
        }
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.DocReceived_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id, int cid = 0)
    {
        DocCat docCat = cid > 0 ? await _docCatService.GetInfo(cid) : null;
        if (id > 0)
        {
            EditDocReceived data = await _docReceivedService.GetEditAsync(id);
            List<Attment> attments = null;
            if (!string.IsNullOrEmpty(data.Attments))
            {
                List<int> attIds = data.Attments.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                attments = await _attment.GetListAsync(attIds);
            }
            return Success(new { data, docCat, attments });
        }
        else return Success(new { docCat });
    }
    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.DocReceived_AddOrEdit)]
    [Log(Name = "新增收文")]
    public async Task<IActionResult> CreateAsync([FromBody] DocReceived post)
    {
        ILoginUserInfo adminUser = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        post.Uid = adminUser.UserId;
        int res = await _docReceivedService.InsertReturnIdAsync(post);
        if (res > 0)
            return Success($"新增收文:{post.Title}; Id: {post.Id}");
        else return Fail("新增失败！");
    }
    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.DocReceived_AddOrEdit)]
    [Log(Name = "修改收文")]
    public async Task<IActionResult> EditAsync([FromBody] EditDocReceived post)
    {
        ILoginUserInfo userInfo = await _applicationContext.ILoginUserInfoMethods.LoginUserInfoAsync();
        if (userInfo.GroupId != 1 && userInfo.UserId != post.Uid)
            return Fail("不能修改别人的内容！");
        DocReceived docReceived = post.Adapt<DocReceived>();
        if (0 < await _docReceivedService.UpdateAsync(docReceived))
            return Success($"修改收文:{post.Title} ID：{post.Id}");
        else return Fail("修改失败！");
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.DocReceived_Delete)]
    [Log(Name = "删除收文")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _docReceivedService.DeleteAsync(id) > 0)
            return Success("删除收文 ID：" + id);
        else return Fail("删除失败！");
    }

}
